package com.example.itcompanyinterview;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.example.itcompanyinterview.tools.CommonJsonParser;
import com.example.itcompanyinterview.tools.CommonUrlRequest;
import com.example.itcompanyinterview.tools.CustomTitleSetter;
import com.example.itcompanyinterview.tools.LoadingDialogHelper;
import com.example.itcompanyinterview.tools.TitleBarGenerator;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class FeedBackActivity extends Activity {

	private static String FEEDBACK_CONTROLLER = "Feedback";
	private static String FEEDBACK_SUBMIT_ACTION = "PostFeedback";
	private LoadingDialogHelper loadingHelper;
	private Handler messageHandler;
	private static int POST_FEEDBACK_FINISHED = 0x01;
	private CustomTitleSetter _titleBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_feed_back);
        _titleBar = new CustomTitleSetter(this);
        _titleBar.setTitle("意见反馈", View.GONE, View.VISIBLE);
    	
    	this.setSubmitAction();
    	this.init();
	}
	
	private void init() {
		this.loadingHelper = new LoadingDialogHelper(this);
		this.initMessageHandler();
	}
	
	private void initMessageHandler() {
    	this.messageHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == POST_FEEDBACK_FINISHED) {
					loadingHelper.closeLoadingDialog();
					String postResponse = (String)msg.obj;
			    	if(postResponse == null) {
			    		Toast.makeText(FeedBackActivity.this, "提交失败，请稍后重试", Toast.LENGTH_SHORT).show();
			    		return;
			    	}
			    	parsePostResponse(postResponse);
				}
				super.handleMessage(msg);
			}
    		
    	};
    }
	
	private void parsePostResponse(String responseJson) {
		try {
			JSONObject response = CommonJsonParser.parseJsonObject(responseJson);
			if (response == null || response.getInt("err") != 0) {
				Toast.makeText(FeedBackActivity.this, "提交反馈异常，请重试", 
						Toast.LENGTH_LONG).show();
				String errmsg = "";
				if(response != null) {
					errmsg = response.getString("msg");
				}
				Log.e("PostFeedback", errmsg);
				return;
			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("反馈已提交")
					   .setMessage("谢谢您的宝贵意见!")
				       .setCancelable(false)
				       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   	finish();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
			}
		}catch(Exception e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}
	
	private void setSubmitAction(){
		Button answerButton = (Button) this.findViewById(R.id.feedback_button);
		answerButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				postFeedback();
			}
		});
	}
	
	private void postFeedback() {
		EditText contentEditor = (EditText)this.findViewById(R.id.feedback_content);
		EditText emailEditor = (EditText)this.findViewById(R.id.feedback_email);
		final String content = contentEditor.getText().toString();
		final String email = emailEditor.getText().toString();
		if(content.equals("") || email.equals("")) {
			Toast.makeText(getApplicationContext(), "内容和Email均不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		
		new Thread(new Runnable(){
			public void run() {	
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("feedback_content", content));
				params.add(new BasicNameValuePair("feedback_email", email));
				String response = CommonUrlRequest.postControllerAndAction(FEEDBACK_CONTROLLER, FEEDBACK_SUBMIT_ACTION, params);
				Message m = messageHandler.obtainMessage();
				m.obj = response;
				m.what = POST_FEEDBACK_FINISHED;
				messageHandler.sendMessage(m);
			}
		}).start();
		this.loadingHelper.showLoadingDialog("反馈提交中", "请稍后...");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}
}
